import React, { Component, createRef } from 'react'
import Styles from './index.module.css'
export default class Sticky extends Component {
  handlScroll = () => {
    // 吸顶内容的dom
    const contentEl = this.contentRef.current
    // 默认占位的dom
    const placeholderEl = this.placeholderRef.current
    const placeholderPosition = placeholderEl.getBoundingClientRect()
    if (placeholderPosition.top <= 0) {
      contentEl.classList.add(Styles.fixed)
      placeholderEl.style.height = this.props.height + 'px'
    } else {
      contentEl.classList.remove(Styles.fixed)
      placeholderEl.style.height = '0px'
    }
  }

  contentRef = createRef()
  placeholderRef = createRef()

  componentDidMount() {
    window.addEventListener('scroll', this.handlScroll)
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handlScroll)
  }

  render() {
    return (
      <div>
        {/* 默认占位 */}
        <div ref={this.placeholderRef}></div>
        {/* 吸顶内容 className={Styles.fixed} */}
        <div ref={this.contentRef}>{this.props.children}</div>
      </div>
    )
  }
}
